package com.tz.movie.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.tz.movie.domain.User;
import com.tz.movie.domain.UserExample;
import com.tz.movie.domain.status;
import com.tz.movie.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Login {

  @Autowired
  UserMapper usermapperimpl;

  @PostMapping(value = "/logout")
  public String logout(HttpServletRequest request, HttpSession session) {
    session.setAttribute("userbase", null);
    JSONObject result = new JSONObject();

    result.put("result", status.s_ok);
    return result.toJSONString();
  }

  @PostMapping("/login")
  public String login(@RequestBody JSONObject jsonparm, HttpServletRequest request, HttpSession session) {
    JSONObject result = new JSONObject();

    if (jsonparm == null) {
      result.put("result", status.s_error);
      return result.toJSONString();
    }
    
    UserExample userExample = new UserExample();
    UserExample.Criteria criteria = userExample.createCriteria();
    criteria.andNameEqualTo((String) jsonparm.get("name"));
    List<User> users = usermapperimpl.selectByExample(userExample);
    if (users != null && users.size() > 0) {
      if (users.get(0).getPassword().equals((String) jsonparm.get("pass"))) {
        result.put("result", status.s_ok);
        result.put("userbase", users.get(0).toString());
        session.setAttribute("userbase", users.get(0).toString());
        return result.toJSONString();
      } else {
        result.put("result", status.s_error);
        return result.toJSONString();
      }
    } else {
      if (users.size() < 0)
        result.put("result", "users null");
      result.put("result", status.s_error);
      return result.toJSONString();
    }
  }

  // @GetMapping("/go")
  // public ModelAndView go(String nameString, String pass) {
  //
  // ModelAndView mView = new ModelAndView();
  // mView.setViewName("NewFile");
  // return mView;
  // }
}
